<template>
  <div class="relative">
    <!-- 铃铛图标 -->
    <button
      @click="toggleDropdown"
      class="relative p-2 text-gray-600 hover:text-gray-900 focus:outline-none"
    >
      <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
      </svg>

      <!-- 未读数量标记 -->
      <span
        v-if="unreadCount > 0"
        class="absolute top-0 right-0 -mt-1 -mr-1 px-1.5 py-0.5 bg-red-500 text-white text-xs rounded-full"
      >
        {{ unreadCount > 99 ? '99+' : unreadCount }}
      </span>
    </button>

    <!-- 下拉菜单 -->
    <transition
      enter-active-class="transition ease-out duration-200"
      enter-from-class="opacity-0 transform scale-95"
      enter-to-class="opacity-100 transform scale-100"
      leave-active-class="transition ease-in duration-150"
      leave-from-class="opacity-100 transform scale-100"
      leave-to-class="opacity-0 transform scale-95"
    >
      <div
        v-show="showDropdown"
        class="absolute right-0 mt-2 w-96 bg-white rounded-lg shadow-xl z-50 overflow-hidden"
      >
        <!-- 标题栏 -->
        <div class="px-4 py-3 bg-gray-50 border-b flex justify-between items-center">
          <h3 class="text-lg font-semibold text-gray-900">通知</h3>
          <div class="flex items-center space-x-2">
            <button
              v-if="unreadCount > 0"
              @click="markAllAsRead"
              class="text-sm text-blue-600 hover:text-blue-800"
            >
              全部标记已读
            </button>
            <Link
              href="/profile/notifications"
              class="text-sm text-gray-600 hover:text-gray-900"
            >
              查看全部
            </Link>
          </div>
        </div>

        <!-- 通知列表 -->
        <div class="max-h-96 overflow-y-auto">
          <div v-if="loading" class="py-8 text-center">
            <div class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
          </div>

          <div v-else-if="notifications.length === 0" class="py-8 text-center text-gray-500">
            <svg class="mx-auto h-8 w-8 text-gray-400 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
            </svg>
            暂无新通知
          </div>

          <div v-else class="divide-y divide-gray-200">
            <div
              v-for="notification in notifications.slice(0, 5)"
              :key="notification.id"
              @click="handleNotificationClick(notification)"
              :class="[
                'px-4 py-3 hover:bg-gray-50 cursor-pointer transition-colors',
                !notification.is_read && 'bg-blue-50'
              ]"
            >
              <div class="flex items-start space-x-3">
                <!-- 图标 -->
                <div
                  :class="[
                    'w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0',
                    getNotificationColor(notification.type)
                  ]"
                >
                  <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                    <path v-if="notification.type === 'like'" d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
                    <path v-else-if="notification.type === 'comment'" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" />
                    <path v-else-if="notification.type === 'follow'" d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
                    <path v-else d="M10 2a6 6 0 00-6 6v3.586l-.707.707A1 1 0 004 14h12a1 1 0 00.707-1.707L16 11.586V8a6 6 0 00-6-6zM10 18a3 3 0 01-3-3h6a3 3 0 01-3 3z" />
                  </svg>
                </div>

                <!-- 内容 -->
                <div class="flex-1 min-w-0">
                  <p class="text-sm font-medium text-gray-900">
                    {{ notification.title }}
                  </p>
                  <p class="text-sm text-gray-600 truncate">
                    {{ notification.content }}
                  </p>
                  <p class="text-xs text-gray-500 mt-1">
                    {{ formatTime(notification.created_at) }}
                  </p>
                </div>

                <!-- 未读标记 -->
                <div v-if="!notification.is_read" class="flex-shrink-0">
                  <div class="w-2 h-2 bg-blue-600 rounded-full"></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部查看更多 -->
        <div v-if="notifications.length > 5" class="px-4 py-3 bg-gray-50 border-t text-center">
          <Link
            href="/profile/notifications"
            class="text-sm text-blue-600 hover:text-blue-800"
          >
            查看所有通知
          </Link>
        </div>
      </div>
    </transition>

    <!-- 点击外部关闭下拉菜单 -->
    <div
      v-if="showDropdown"
      @click="showDropdown = false"
      class="fixed inset-0 z-40"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Link } from '@inertiajs/inertia-vue3'
import axios from 'axios'

const showDropdown = ref(false)
const notifications = ref([])
const unreadCount = ref(0)
const loading = ref(false)

// 切换下拉菜单
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
  if (showDropdown.value) {
    loadNotifications()
  }
}

// 获取通知颜色
const getNotificationColor = (type) => {
  const colors = {
    follow: 'bg-blue-500',
    comment: 'bg-green-500',
    like: 'bg-red-500',
    favorite: 'bg-yellow-500',
    system: 'bg-gray-500',
    post_approved: 'bg-green-600',
    post_rejected: 'bg-red-600',
  }
  return colors[type] || 'bg-gray-500'
}

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else {
    return date.toLocaleDateString()
  }
}

// 加载通知
const loadNotifications = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/notifications', {
      params: {
        per_page: 10
      }
    })
    notifications.value = response.data.notifications
    unreadCount.value = response.data.unread_count
  } catch (error) {
    console.error('加载通知失败:', error)
  } finally {
    loading.value = false
  }
}

// 标记全部已读
const markAllAsRead = async () => {
  try {
    await axios.post('/api/notifications/mark-all-as-read')
    notifications.value.forEach(n => {
      n.is_read = true
    })
    unreadCount.value = 0
  } catch (error) {
    console.error('标记失败:', error)
  }
}

// 点击通知
const handleNotificationClick = async (notification) => {
  showDropdown.value = false

  // 标记为已读
  if (!notification.is_read) {
    try {
      await axios.post(`/api/notifications/${notification.id}/mark-as-read`)
      notification.is_read = true
      unreadCount.value--
    } catch (error) {
      console.error('标记失败:', error)
    }
  }

  // 跳转到相关页面
  if (notification.data?.post_slug) {
    window.location.href = `/posts/${notification.data.post_slug}`
  } else if (notification.data?.user_username) {
    window.location.href = `/profile/${notification.data.user_username}`
  }
}

// 获取未读数量
const loadUnreadCount = async () => {
  try {
    const response = await axios.get('/api/notifications/unread-count')
    unreadCount.value = response.data.count
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 定时刷新未读数量
let intervalId = null

onMounted(() => {
  loadUnreadCount()
  // 每30秒刷新一次未读数量
  intervalId = setInterval(loadUnreadCount, 30000)
})

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId)
  }
})
</script>